package model

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"server/common"
	"server/pkg/setting"
	"time"
)

type LocalTime time.Time

func (t *LocalTime) MarshalJSON() ([]byte, error) {
	tTime := time.Time(*t)
	return []byte(fmt.Sprintf("\"%v\"", tTime.Format("2006-01-02 15:04:05"))), nil
}

type Model struct {
	ID        int        `gorm:"primaryKey;" json:"id"`
	CreatedAt *LocalTime `gorm:"column:ctime;type:TIMESTAMP;default:CURRENT_TIMESTAMP();<-:create" json:"ctime,omitempty"`
	UpdatedAt *LocalTime `gorm:"column:utime;type:TIMESTAMP;default:CURRENT_TIMESTAMP()  on update CURRENT_TIMESTAMP()" json:"utime"`
	DeletedAt *LocalTime `sql:"index" gorm:"column:dtime;type:DATETIME" json:"dtime"`
}

type Bmodel interface {
}

type UModel struct {
	Model
}

func NewDBEngine(databaseSetting *setting.DatabaseSettingS) (*gorm.DB, error) {
	s := "%s:%s@tcp(%s)/%s?charset=%s&parseTime=%t&loc=Local"
	DSN := fmt.Sprintf(s,
		databaseSetting.UserName,
		databaseSetting.Password,
		databaseSetting.Host,
		databaseSetting.DBName,
		databaseSetting.Charset,
		databaseSetting.ParseTime,
	)
	db, err := gorm.Open(mysql.New(mysql.Config{
		DSN:                       DSN,   // DSN data source name
		DefaultStringSize:         256,   // string 类型字段的默认长度
		DisableDatetimePrecision:  true,  // 禁用 datetime 精度，MySQL 5.6 之前的数据库不支持
		DontSupportRenameIndex:    true,  // 重命名索引时采用删除并新建的方式，MySQL 5.7 之前的数据库和 MariaDB 不支持重命名索引
		DontSupportRenameColumn:   true,  // 用 `change` 重命名列，MySQL 8 之前的数据库和 MariaDB 不支持重命名列
		SkipInitializeWithVersion: false, // 根据当前 MySQL 版本自动配置
	}), &gorm.Config{})

	if err != nil {
		return nil, err
	}

	return db, nil
}

func addExtraSpaceIfExist(str string) string {
	if str != "" {
		return " " + str
	}
	return ""
}

func (m *Model) Info() error {
	if err := common.DB.Where("id = ?", m.ID).Find(&m).Error; err != nil {
		return err
	}
	return nil
}

func (m *Model) Create() error {
	if err := common.DB.Create(&m).Error; err != nil {
		return err
	}
	return nil
}

func (m *Model) Update() error {
	if err := common.DB.Where("id = ?", m.ID).Updates(&m).Error; err != nil {
		return err
	}
	return nil
}

func (m *Model) Delete() error {
	if err := common.DB.Where("id = ?", m.ID).Delete(&m).Error; err != nil {
		return err
	}
	return nil
}
